﻿using Future.Common;
using Future.Web.Utility;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace Future.Web.Extensions
{
    /// <summary>
    /// jwt扩展
    /// </summary>
    public static class JwtExtension
    {
        /// <summary>
        /// jwt配置节点名称
        /// </summary>
        public const string JWTAUTHORIZE = "JwtAuthorize";

        /// <summary>
        /// 注册jwt鉴权服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddJwtService(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure<JwtTokenOptions>(configuration.GetSection(JWTAUTHORIZE));
            services.AddTransient<JwtInvoker>();
            var jwtOptions = configuration.GetSection(JWTAUTHORIZE).Get<JwtTokenOptions>();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                             .AddJwtBearer(options =>
                             {
                                 options.Events = new JwtBearerEvents
                                 {
                                     OnAuthenticationFailed = (context) =>
                                     {
                                         return Task.CompletedTask;
                                     },
                                     OnMessageReceived = (context) =>
                                     {
                                         return Task.CompletedTask;
                                     },
                                     OnChallenge = (context) =>
                                     {
                                         return Task.CompletedTask;
                                     },
                                 };

                                 options.TokenValidationParameters = new TokenValidationParameters
                                 {
                                     ClockSkew = TimeSpan.Zero,//过期缓冲时间
                                     ValidateIssuer = true,//是否验证Issuer
                                     ValidateAudience = true,//是否验证Audience
                                     ValidateLifetime = true,//是否验证失效时间
                                     ValidateIssuerSigningKey = true,//是否验证SecurityKey
                                     ValidAudience = jwtOptions.Audience,//Audience
                                     ValidIssuer = jwtOptions.Issuer,//Issuer，这两项和前面签发jwt的设置一致
                                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.Secret))
                                 };
                             });

            return services;
        }
    }
}
